import { useEffect, useState, useRef, useMemo } from "react";
import { Link, useLocation } from "react-router-dom";
import styles from "./index.module.scss";
import thumb1 from "../../assets/thumb/thumb1.png";
import thumb2 from "../../assets/thumb/thumb2.png";
import thumb3 from "../../assets/thumb/thumb3.png";
import { useSelector } from "react-redux";

declare const window: any;

type ContentItem = {
  id: number;
  name: string;
  thumb: string;
  url?: string;
  type: "video" | "article";
};

const allGrades = ["小班上", "小班下", "中班上", "中班下", "大班上", "大班下", "托班上", "托班下"];
const contentTypes = ["视频", "文章"];

// 示例数据
const sampleVideoList: ContentItem[] = [
  { id: 1, name: "小班上——\"我上幼儿...\"", thumb: thumb1, url: "https://media.w3.org/2010/05/sintel/trailer.mp4", type: "video" },
  { id: 2, name: "小班上——\"玩玩乐\"主题", thumb: thumb2, url: "https://media.w3.org/2010/05/bunny/trailer.mp4", type: "video" },
  { id: 3, name: "小班上——\"探索自然\"主题", thumb: thumb3, url: "https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4", type: "video" },
  { id: 4, name: "小班上——\"快乐成长\"主题", thumb: thumb1, url: "https://media.w3.org/2010/05/sintel/trailer.mp4", type: "video" },
];

const sampleArticleList: ContentItem[] = [
  { id: 101, name: "小班上——课程实施指南", thumb: thumb2, type: "article" },
  { id: 102, name: "小班上——教学方法解析", thumb: thumb3, type: "article" },
  { id: 103, name: "小班上——活动设计要点", thumb: thumb1, type: "article" },
];

const useQuery = () => {
  const { search } = useLocation();
  return useMemo(() => new URLSearchParams(search), [search]);
};

const HomeEducationPage = () => {
  const systemConfig = useSelector((state: any) => state.systemConfig.value);
  const query = useQuery();
  const initGrade = query.get("grade") || "小班上";
  const initType = query.get("type") || "视频";
  
  const [grade, setGrade] = useState(initGrade);
  const [contentType, setContentType] = useState<"视频" | "文章">(initType as "视频" | "文章" || "视频");
  const [showPlayer, setShowPlayer] = useState(false);
  const [current, setCurrent] = useState<ContentItem | null>(null);
  const playerInitedRef = useRef(false);

  useEffect(() => {
    document.title = `家园共育资源库 · ${grade} · ${contentType}`;
  }, [grade, contentType]);

  useEffect(() => {
    if (showPlayer && current && current.url && !playerInitedRef.current) {
      initDPlayer(current.url);
      playerInitedRef.current = true;
    }
    return () => {
      if (!showPlayer && window.player) {
        try {
          window.player.destroy();
        } catch {}
        playerInitedRef.current = false;
      }
    };
  }, [showPlayer, current]);

  const initDPlayer = (playUrl: string) => {
    window.player = new window.DPlayer({
      container: document.getElementById("meedu-player-container"),
      autoplay: false,
      video: {
        url: playUrl,
        pic: systemConfig.playerPoster || "",
      },
    });
  };

  // 根据类型和年级筛选内容
  const getFilteredContent = () => {
    if (contentType === "视频") {
      return sampleVideoList;
    } else {
      return sampleArticleList;
    }
  };

  const handleContentClick = (item: ContentItem) => {
    if (item.type === "video" && item.url) {
      setCurrent(item);
      setShowPlayer(true);
    } else if (item.type === "article") {
      // 文章点击可以跳转到详情页或显示详情
      // 这里暂时不做处理，后续可以添加文章详情页
      console.log("查看文章:", item.name);
    }
  };

  return (
    <div className={styles.page}>
      <div className={styles.header}>
        <Link to="/" aria-label="关闭" className={styles.close}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true">
            <path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
          </svg>
        </Link>
        <div className={styles.title}>家园共育资源库</div>
        <div style={{ width: 32 }} />
      </div>

      <div className={styles.tabs}>
        <div className={styles.tabGroup}>
          <div className={styles.tabLabel}>年龄段:</div>
          {allGrades.map((g) => (
            <button
              key={g}
              className={`${styles.tab} ${grade === g ? styles.tabActive : ""}`}
              onClick={() => setGrade(g)}
            >
              {g}
            </button>
          ))}
        </div>
      </div>

      <div className={styles.typeTabs}>
        {contentTypes.map((type) => (
          <button
            key={type}
            className={`${styles.typeTab} ${contentType === type ? styles.typeTabActive : ""}`}
            onClick={() => setContentType(type as "视频" | "文章")}
          >
            {type}
          </button>
        ))}
      </div>

      <div className={styles.grid}>
        {getFilteredContent().map((item) => (
          <div
            key={item.id}
            className={styles.card}
            onClick={() => handleContentClick(item)}
          >
            <div className={styles.thumbWrap}>
              <img className={styles.thumb} src={item.thumb} alt={item.name} />
              {item.type === "video" && (
                <span className={styles.playIcon} aria-hidden="true">
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M8 5v14l11-7z" />
                  </svg>
                </span>
              )}
              {item.type === "article" && (
                <span className={styles.articleIcon} aria-hidden="true">
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6z" />
                    <path d="M14 2v6h6" />
                    <path d="M16 13H8" />
                    <path d="M16 17H8" />
                    <path d="M10 9H8" />
                  </svg>
                </span>
              )}
            </div>
            <div className={styles.name}>{item.name}</div>
          </div>
        ))}
      </div>

      <div className={styles.loadMore}>--加载更多--</div>

      {showPlayer && current && current.url && (
        <div className={styles.mask} onClick={() => setShowPlayer(false)}>
          <div className={styles.playerPanel} onClick={(e) => e.stopPropagation()}>
            <div className={styles.playerHeader}>
              <div>{current.name}</div>
              <button className={styles.closeBtn} onClick={() => setShowPlayer(false)}>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                  <path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
                </svg>
              </button>
            </div>
            <div id="meedu-player-container" className={styles.playerBody}></div>
          </div>
        </div>
      )}
    </div>
  );
};

export default HomeEducationPage;

